package com.pay.modules.web.controller;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pay.common.constants.Constants;
import com.pay.common.constants.CourierStatus;
import com.pay.common.constants.PayStatus;
import com.pay.common.model.RespEntity;
import com.pay.common.util.DateUtils;
import com.pay.payment.entity.Courier;
import com.pay.payment.entity.Pay;
import com.pay.payment.entity.Product;
import com.pay.payment.entity.User;
import com.pay.payment.service.ICourierService;
import com.pay.payment.service.IPayService;
import com.pay.payment.service.IProductService;
import com.pay.payment.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Api(tags ="支付数据")
@Controller
@RequestMapping(value = "data")
public class DataController {

	@Autowired
	IUserService userService;
	@Autowired
	IProductService productService;
	@Autowired
	IPayService payService;
	@Autowired
	ICourierService courierService;

	private static final Logger logger = LoggerFactory.getLogger(DataController.class);


	@ApiOperation(value="订单数据")
	@ResponseBody
	@RequestMapping(value="listPayOrder",method=RequestMethod.POST)
	public JSONObject order( @RequestParam(value = "pageNo") int pageNo,
							@RequestParam(value = "pageSize") int pageSize,
							 @RequestParam(value = "keywords") String keywords) {
		logger.info("==========[listPayOrder]======  keywords ={}",keywords);
		JSONObject jsonObject = new JSONObject();
		Page pageModel =new Page();
		pageModel.setSize(pageNo*pageSize);
		pageModel.setCurrent(pageNo);
		pageModel.addOrder(OrderItem.desc("create_time"));
		QueryWrapper query = new QueryWrapper<Pay>();
		if(StringUtils.isNotBlank(keywords)){
			Object	mobile	 =JSONObject.parseObject(keywords).get("keywords");
			Object	status	= JSONObject.parseObject(keywords).get("status");
			if(ObjectUtil.isNotEmpty(mobile)){
				query.eq("mobile",JSONObject.parseObject(keywords).get("keywords"));
			}
			if(ObjectUtil.isNotEmpty(status)){
				query.eq("status",JSONObject.parseObject(keywords).get("status"));
			}
		}
		IPage<Pay> list = payService.page(pageModel,query);

		//支付状态(0= 申请成功 1=支付成功 2=支付中 3=支付失败 4=退货中 5=退货失败 6退货完成 7申请失败)
		for (Pay record : list.getRecords()) {
			record.setStatusDesc(PayStatus.getName(record.getStatus()));
		}
		jsonObject.put("list",list.getRecords());
		jsonObject.put("count",list.getSize());
		return jsonObject;
	}

	@ApiOperation(value="用户数据")
	@ResponseBody
	@RequestMapping(value="listPayUser",method=RequestMethod.POST)
	public JSONObject user( @RequestParam(value = "pageNo") int pageNo,
							@RequestParam(value = "pageSize") int pageSize,
							@RequestParam(value = "keywords") String keywords) {
		logger.info("==========[listPayUser]======  keywords ={}",keywords);
		JSONObject jsonObject = new JSONObject();
		Page pageModel =new Page();
		pageModel.setSize(pageNo*pageSize);
		pageModel.setCurrent(pageNo);
		QueryWrapper query = new QueryWrapper<User>();
		if(StringUtils.isNotBlank(keywords)){
			query.eq("mobile",JSONObject.parseObject(keywords).get("keywords"));
		}
		IPage<User> list = userService.page(pageModel,query);
		jsonObject.put("list",list.getRecords());
		jsonObject.put("count",list.getSize());
		return jsonObject;
	}

	@ApiOperation(value="产品数据")
	@ResponseBody
	@RequestMapping(value="listPayProduct",method=RequestMethod.POST)
	public JSONObject product( @RequestParam(value = "pageNo") int pageNo,
							 @RequestParam(value = "pageSize") int pageSize,
								@RequestParam(value = "keywords") String keywords) {
		logger.info("==========[listPayProduct]======  keywords ={}",keywords);
		JSONObject jsonObject = new JSONObject();
		Page pageModel =new Page();
		pageModel.setSize(pageNo*pageSize);
		pageModel.setCurrent(pageNo);
		QueryWrapper query = new QueryWrapper<Product>();
		if(StringUtils.isNotBlank(keywords)){
			query.eq("people_phone",JSONObject.parseObject(keywords).get("keywords"));
		}
		IPage<Product> list = productService.page(pageModel,query);
		jsonObject.put("list",list.getRecords());
		jsonObject.put("count",list.getSize());
		return jsonObject;
	}

	@ApiOperation(value="物流数据")
	@ResponseBody
	@RequestMapping(value="listPayCourier",method=RequestMethod.POST)
	public JSONObject courier( @RequestParam(value = "pageNo") int pageNo,
							   @RequestParam(value = "pageSize") int pageSize,
							   @RequestParam(value = "keywords") String keywords) {
		logger.info("==========[listPayCourier]======  keywords ={}",keywords);
		JSONObject jsonObject = new JSONObject();
		Page pageModel =new Page();
		pageModel.setSize(pageNo*pageSize);
		pageModel.setCurrent(pageNo);
		QueryWrapper query = new QueryWrapper<Courier>();
		if(StringUtils.isNotBlank(keywords)){
			Object	mobile	 =JSONObject.parseObject(keywords).get("keywords");
			Object	status	= JSONObject.parseObject(keywords).get("status");
			if(ObjectUtil.isNotEmpty(mobile)){
				query.eq("customer_phone",JSONObject.parseObject(keywords).get("keywords"));
			}
			if(ObjectUtil.isNotEmpty(status)){
				query.eq("status",JSONObject.parseObject(keywords).get("status"));
			}
		}
		IPage<Courier> list = courierService.page(pageModel,query);
		for (Courier record : list.getRecords()) {
			record.setStatusDesc(CourierStatus.getName(record.getStatus()));
		}
		jsonObject.put("list",list.getRecords());
		jsonObject.put("count",list.getSize());
		return jsonObject;
	}


	@ApiOperation(value="物流查询")
	@ResponseBody
	@RequestMapping(value = "courierQuery", method={ RequestMethod.POST})
	public RespEntity query(@RequestParam(value = "seqNo") String seqNo) {
        RespEntity respEntity = new RespEntity(Constants.Systems.FAIL,Constants.Systems.SYSTEM_ERROR_CODE);

        logger.info("==========[orderCourierQuery]======  seqNo ={}",seqNo);
		try {
			Courier courier = courierService.getOne(new LambdaQueryWrapper<Courier>().eq(Courier::getCourierId,seqNo).last(" limit 1"));
			if(courier!=null){
                respEntity.setStatus(Constants.Systems.OK);
                respEntity.setCode(Constants.Systems.SERVER_SUCCESS);
                respEntity.setData(courier);
			}
		} catch (Exception e) {
			logger.error("==========[CourierController. Exception]->:{}", e);
		}
		return respEntity;
	}

	@ApiOperation(value="物流新增")
	@ResponseBody
	@RequestMapping(value = "courierInsert", method={ RequestMethod.POST})
	public JSONObject insert(@RequestParam(value = "seqNo") String seqNo
			,@RequestParam(value = "courierNo") String courierNo
			,@RequestParam(value = "num") String num
			,@RequestParam(value = "courierAmount") String courierAmount
			,@RequestParam(value = "courierCompany") String courierCompany) {
		JSONObject jsonObject = new JSONObject();
		logger.info("==========[orderCourierInsert]======  seqNo ={}",seqNo);
		Pay pay =	payService.getOne(new LambdaQueryWrapper<Pay>().eq(Pay::getSeqNo,seqNo));
		if(pay ==null){
			jsonObject.put("msg","订单信息不存在");
			return jsonObject;
		}
		try {
			logger.info("==========[orderCourierInsert]======  courierNo ={}",courierNo);
			if(Objects.isNull(courierNo)){
				jsonObject.put("msg","请填写快递公司");
				return jsonObject;
			}
			logger.info("==========[orderCourierInsert]======  courierCompany ={}",courierCompany);
			if(StringUtils.isEmpty(courierCompany)){
				jsonObject.put("msg","请填写快递编号");
				return jsonObject;
			}
			Courier courier = new Courier();
			courier.setCourierId(seqNo);
			courier.setCstId(pay.getCstId());
			courier.setAppId(pay.getAppId());
			courier.setCustomerName(pay.getUserName());
			courier.setCustomerPhone(pay.getMobile());
			courier.setParentId(pay.getParentId());
			courier.setProductId(pay.getProductId());
			courier.setCustomerAddress(pay.getSource());
			courier.setCourierNo(courierNo);
			courier.setCourierCompany(courierCompany);
			courier.setCourierAmount(new BigDecimal(courierAmount));
			courier.setNum(Integer.valueOf(num));
			Boolean i = courierService.save(courier);
			if(i){
				jsonObject.put("msg","成功");
				return jsonObject;
			}
		} catch (Exception e) {
			logger.error("==========[CourierController. Exception]->:{}", e);
			jsonObject.put("msg","金额或者数量填写错误！");
			return jsonObject;
		}
		logger.info("==========[orderCourierInsert]======respEntity ={}",jsonObject);
		return jsonObject;
	}

	@ApiOperation(value="物流修改")
	@ResponseBody
	@RequestMapping(value = "courierUpdate", method={ RequestMethod.POST})
	public JSONObject update(@RequestParam(value = "seqNo") String seqNo
			,@RequestParam(value = "status") String status) {
		JSONObject jsonObject = new JSONObject();
		try {
			logger.info("==========[orderCourierUpdate]======  status ={}",status);
			Courier courier = courierService.getOne(new LambdaQueryWrapper<Courier>().eq(Courier::getCourierId,seqNo).last(" limit 1"));
			if(courier!=null){
				/*courier.setCourierNo(courierNo);
				courier.setCourierCompany(courierCompany);*/
				courier.setStatus(Integer.valueOf(status));
				Boolean i =courierService.saveOrUpdate(courier);
				if(i){
					jsonObject.put("msg","成功");
					return jsonObject;
				}
			}
		} catch (Exception e) {
			logger.error("==========[CourierController. Exception]->:{}", e);
		}
		return jsonObject;
	}
}
